"""
证书模块API视图
"""
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from django.db.models import Q

from .models import Certificate
from .serializers import CertificateSerializer


class CertificateViewSet(viewsets.ModelViewSet):
    """
    证书管理ViewSet
    
    提供证书的CRUD操作:
        - list: 获取证书列表（支持按类别、级别、等级筛选）
        - retrieve: 获取证书详情
        - create: 创建证书类型（仅管理员）
        - update: 更新证书信息（仅管理员）
        - destroy: 删除证书（仅管理员）
    """
    queryset = Certificate.objects.all()
    serializer_class = CertificateSerializer
    permission_classes = [IsAuthenticated]
    
    def get_queryset(self):
        """
        获取查询集
        
        支持按类别、级别、等级筛选
        """
        queryset = Certificate.objects.all()
        
        # 类别筛选
        sort = self.request.query_params.get('sort', None)
        if sort:
            queryset = queryset.filter(sort=sort)
        
        # 级别筛选
        ranks = self.request.query_params.get('ranks', None)
        if ranks:
            queryset = queryset.filter(ranks=ranks)
        
        # 等级筛选
        classes = self.request.query_params.get('classes', None)
        if classes:
            queryset = queryset.filter(classes=classes)
        
        # 搜索功能
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(
                Q(name__icontains=search) |
                Q(sort__icontains=search) |
                Q(ranks__icontains=search) |
                Q(classes__icontains=search)
            )
        
        return queryset
    
    def create(self, request, *args, **kwargs):
        """
        创建证书类型
        
        权限：仅管理员可创建
        """
        if not request.user.is_staff:
            return Response({
                'code': 403,
                'message': '权限不足，仅管理员可创建证书类型'
            }, status=status.HTTP_403_FORBIDDEN)
        
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        
        return Response({
            'code': 201,
            'message': '创建成功',
            'data': serializer.data
        }, status=status.HTTP_201_CREATED)
    
    def update(self, request, *args, **kwargs):
        """
        更新证书信息
        
        权限：仅管理员可更新
        """
        if not request.user.is_staff:
            return Response({
                'code': 403,
                'message': '权限不足，仅管理员可更新证书'
            }, status=status.HTTP_403_FORBIDDEN)
        
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        
        return Response({
            'code': 200,
            'message': '更新成功',
            'data': serializer.data
        })
    
    def destroy(self, request, *args, **kwargs):
        """
        删除证书
        
        权限：仅管理员可删除
        """
        if not request.user.is_staff:
            return Response({
                'code': 403,
                'message': '权限不足，仅管理员可删除证书'
            }, status=status.HTTP_403_FORBIDDEN)
        
        instance = self.get_object()
        self.perform_destroy(instance)
        
        return Response({
            'code': 204,
            'message': '删除成功'
        }, status=status.HTTP_204_NO_CONTENT)
